"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" This vimrc is based on the vimrc by Amix - http://amix.dk/
"
" Maintainer: wang hua
" Version: 0.1
" Last Change:
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" 	Shortcuts
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" for TagBar
nmap <silent> <F7> :TagbarToggle<CR> 
let g:tagbar_width = 30
" for Doxygen 
let g:DoxygenToolkit_briefTag_pre="@Synopsis  "
let g:DoxygenToolkit_paramTag_pre="@Param "
let g:DoxygenToolkit_returnTag="@Returns   "
let g:DoxygenToolkit_blockHeader="----------------------------start----------------------------------------------"
let g:DoxygenToolkit_blockFooter="-----------------------------end-----------------------------------------------"
let g:DoxygenToolkit_authorName="wang hua"
"let g:DoxygenToolkit_licenseTag=""

" Grep
nnoremap <silent> <F2> :Rgrep<CR>

"Change window
"nmap <F3> <C-W>-
"nmap <F4> <C-W>+

"Tags 
"set tags=/home/wanghua/meego_sdk/meego-kernel-git/linux-2.6.37/tags
set notbs
nnoremap <silent> <F3> :ts<CR>
"A
nnoremap <silent> <F12> :A<CR>

"Quickfix

"Git diff log status add commit
map <leader>gs :GitStatus<cr>
map <leader>gc :GitCommit<cr>
map <leader>ga :GitAdd<cr>
map <leader>gp :GitPush<cr>
map <leader>gl :GitPull<cr>

"cscope
nmap <F4> :cscope find g <C-R>=expand("<cword>")<CR><CR>
nmap <F5> :vert scs find g <C-R>=expand("<cword>")<CR><CR>
"nmap <F6> :vert scs find c <C-R>=expand("<cword>")<CR><CR>
nmap <F6> :cs find c <C-R>=expand("<cword>")<CR><CR>
"Paste toggle - when pasting something in, don't indent.
set pastetoggle=<F7>
"you also can :set paste, :set paste!

"EnhancedCommentify
"vmap <F8> <Esc><Esc>:call EnhancedCommentify('yes','comment',line("'<"),line("'>"))<CR>
"vmap <C-F8> <Esc><Esc>:call EnhancedCommentify('yes','decomment',line("'<"),line("'>"))<CR>

"use NERD_commenter


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" General
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

"Get out of VI's compatible mode..
set nocompatible

" Platform
function! MySys()
    return "linux"
endfunction

"Sets how many lines of history VIM har to remember
set history=500

set encoding=utf-8
set fileencodings=utf-8,chinese,gb2312,gbk,gb18030,big5,latin-1

"Enable filetype plugin
filetype plugin on
filetype indent on

"Set to auto read when a file is changed from the outside
set autoread

"Have the mouse enabled all the time:
"set mouse=a

"Set mapleader
let mapleader = ","
let g:mapleader = ","

"Fast Ex command
nnoremap ; :

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Moving around and tabs
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Smart way to move btw. windows
nmap <C-j> <C-W>j
nmap <C-k> <C-W>k
nmap <C-h> <C-W>h
nmap <C-l> <C-W>l
"Change window
nmap <C-F9> <C-W>>
nmap <C-F10> <C-W>v
nmap <C-F11> <C-W><



"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Colors and Fonts
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
if &term=="xterm"
	set t_Co=8
	set t_Sb=^[[4%dm
	set t_Sf=^[[3%dm
endif

"set term=xterm-256color
" Avoid clearing hilight definition in plugins
if !exists("g:vimrc_loaded")
    "Enable syntax hl
    " color scheme
    if has("gui_running")
        set guioptions-=T
        set guioptions-=m
        set guioptions-=L
        set guioptions-=r
        colorscheme desert_my
        "hi normal guibg=#294d4a
    else
		colorscheme desert_my
    endif " has
endif " exists(...)

syntax enable
set background=dark
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Fileformats
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Favorite filetypes
set ffs=unix,dos

"Turn on WiLd menu
set wildmenu

"Always show current position
set ruler

"The commandbar is 2 high
set cmdheight=2

"Show line number
set nonu

"Do not redraw, when running macros.. lazyredraw
"set lz

"Change buffer - without saving
set hid

"Set backspace
set backspace=eol,start,indent

"Bbackspace and cursor keys wrap to
set whichwrap+=<,>
set nowrap

"Ignore case when searching
set ignorecase

"Include search
set incsearch

"Highlight search things
set hlsearch

"Set magic on
set magic

"No sound on errors.
set noerrorbells
set novisualbell
set t_vb=

""""""""""""""""""""""""""""""
" Statusline
""""""""""""""""""""""""""""""
"Always hide the statusline
set laststatus=2
"set statusline=%F%m%r%h%w\ [FORMAT=%{&ff}]\ [TYPE=%Y]\ [POS=%l,%v][%p%%]\ %{strftime(\"%d/%m/%y\ -\ %H:%M\")}
set statusline=%F%m%r%h%w[F=%{&ff}][%l][%p%%]

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Editing mappings etc.
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Switch to buffer according to file name
"function! SwitchToBuf(filename)
    ""let fullfn = substitute(a:filename, "^\\~/", $HOME . "/", "")
    "" find in current tab
    "let bufwinnr = bufwinnr(a:filename)
    "if bufwinnr != -1
        "exec bufwinnr . "wincmd w"
        "return
    "else
        "" find in each tab
        "tabfirst
        "let tab = 1
        "while tab <= tabpagenr("$")
            "let bufwinnr = bufwinnr(a:filename)
            "if bufwinnr != -1
                "exec "normal " . tab . "gt"
                "exec bufwinnr . "wincmd w"
                "return
            "endif
            "tabnext
            "let tab = tab + 1
        "endwhile
        "" not exist, new tab
        "exec "tabnew " . a:filename
    "endif
"endfunction


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Buffer realted
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Open a dummy buffer for paste
"map <leader>es :tabnew<cr>:setl buftype=nofile<cr>
map <leader>tn :tabnew<cr>:setl buftype=nofile<cr>
if MySys() == "linux"
map <leader>ec :tabnew ~/tmp/scratch.txt<cr>
else
map <leader>ec :tabnew $TEMP/scratch.txt<cr>
endif

"Restore cursor to file position in previous editing session
set viminfo='10,\"100,:20,n~/.viminfo
au BufReadPost * if line("'\"") > 0|if line("'\"") <= line("$")|exe("norm '\"")|else|exe "norm $"|endif|endif

" Don't close window, when deleting a buffer
command! Bclose call <SID>BufcloseCloseIt()

function! <SID>BufcloseCloseIt()
   let l:currentBufNum = bufnr("%")
   let l:alternateBufNum = bufnr("#")

   if buflisted(l:alternateBufNum)
     buffer #
   else
     bnext
   endif

   if bufnr("%") == l:currentBufNum
     new
   endif

   if buflisted(l:currentBufNum)
     execute("bdelete! ".l:currentBufNum)
   endif
endfunction

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Session options
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
set sessionoptions-=curdir
set sessionoptions+=sesdir

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Files and backups
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Turn backup off
set nobackup
set nowb
set noswapfile
"set bufhidden=hide

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Text options
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
au BufRead,BufNewFile * setfiletype txt 
au FileType txt setl lbr
au FileType txt setl tw=120
set iskeyword+=_,$,@,%,#,-

""""""""""""""""""""""""""""""
" Indent
""""""""""""""""""""""""""""""
"set formatoptions=tcrqn
set smarttab
set smartindent
set autoindent
set cindent
set tabstop=4
set softtabstop=4
set shiftwidth=4
set expandtab


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Plugin configuration
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"""""""""""""""""""""""""
"IDE
""""""""""""""""""""""""""""""
" file explorer setting
""""""""""""""""""""""""""""""
"Split vertically
let g:explVertical=1

"Window size
let g:explWinSize=35

let g:explSplitLeft=1
let g:explSplitBelow=1

"Hide some files
let g:explHideFiles='^\.,.*\.class$,.*\.swp$,.*\.pyc$,.*\.swo$,\.DS_Store$'

"Hide the help thing..
let g:explDetailedHelp=0

""""""""""""""""""""""""""""""
" minibuffer setting
""""""""""""""""""""""""""""""
let loaded_minibufexplorer = 1         " *** Disable minibuffer plugin
let g:miniBufExplorerMoreThanOne = 2   " Display when more than 2 buffers
let g:miniBufExplSplitToEdge = 1       " Always at top
let g:miniBufExplMaxSize = 3           " The max height is 3 lines
let g:miniBufExplMapWindowNavVim = 1   " map CTRL-[hjkl]
let g:miniBufExplUseSingleClick = 1    " select by single click
let g:miniBufExplModSelTarget = 1      " Dont change to unmodified buffer
let g:miniBufExplForceSyntaxEnable = 1 " force syntax on
let g:miniBufExplVSplit = 25
let g:miniBufExplSplitBelow = 0

let g:miniBufExplorerMoreThanOne=0
"autocmd BufRead,BufNew :call UMiniBufExplorer

""""""""""""""""""""""""""""""
" bufexplorer setting
""""""""""""""""""""""""""""""
let g:bufExplorerDefaultHelp=1       " Do not show default help.
let g:bufExplorerShowRelativePath=1  " Show relative paths.
let g:bufExplorerSortBy='mru'        " Sort by most recently used.
let g:bufExplorerSplitRight=0        " Split left.
let g:bufExplorerSplitVertical=1     " Split vertically.
let g:bufExplorerSplitVertSize = 30  " Split width
let g:bufExplorerUseCurrentWindow=1  " Open in new window.
let g:bufExplorerMaxHeight=13        " Max height


""""""""""""""""""""""""""""""
" taglist setting
""""""""""""""""""""""""""""""
"let Tlist_Ctags_Cmd = 'ctags'
let Tlist_Show_One_File = 1
let Tlist_Exit_OnlyWindow = 1
let Tlist_File_Fold_Auto_Close=1
let Tlist_Process_File_Always=1
nmap <silent> <leader>tl :Tlist<cr>

""""""""""""""""""""""""""""""
" winmanager setting
""""""""""""""""""""""""""""""
let g:winManagerWindowLayout = "BufExplorer,FileExplorer|TagList"
let g:winManagerWidth = 30
let g:defaultExplorer = 0
nmap <C-W><C-F> :FirstExplorerWindow<cr>
nmap <C-W><C-B> :BottomExplorerWindow<cr>
nmap <silent> <leader>wm :WMToggle<cr>
autocmd BufWinEnter \[Buf\ List\] setl nonumber

""""""""""""""""""""""""""""""
" netrw setting
""""""""""""""""""""""""""""""
let g:netrw_winsize = 30
nmap <silent> <leader>fe :Sexplore!<cr>


""""""""""""""""""""""""""""""
" lookupfile setting
""""""""""""""""""""""""""""""
let g:LookupFile_MinPatLength = 2
let g:LookupFile_PreserveLastPattern = 0
let g:LookupFile_PreservePatternHistory = 0
let g:LookupFile_AlwaysAcceptFirst = 1
let g:LookupFile_AllowNewFiles = 0
if filereadable("./filenametags")
let g:LookupFile_TagExpr = '"./filenametags"'
endif
nmap <silent> <leader>lk <Plug>LookupFile<cr>
nmap <silent> <leader>ll :LUBufs<cr>
nmap <silent> <leader>lw :LUWalk<cr>

" lookup file with ignore case
function! LookupFile_IgnoreCaseFunc(pattern)
let _tags = &tags
try
   let &tags = eval(g:LookupFile_TagExpr)
   let newpattern = '\c' . a:pattern
   let tags = taglist(newpattern)
catch
   echohl ErrorMsg | echo "Exception: " . v:exception | echohl NONE
   return ""
finally
   let &tags = _tags
endtry

" Show the matches for what is typed so far.
let files = map(tags, 'v:val["filename"]')
return files
endfunction
let g:LookupFile_LookupFunc = 'LookupFile_IgnoreCaseFunc'

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"fencview Autodetect multiple encodings 
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
let g:fencview_autodetect = 1 


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"function echo
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"ctags -R --fields=+lS
set foldmethod=syntax
set foldlevel=100

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" MISC
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
"Remove the Windows ^M - :%s/<C-V><cr>//ge

set updatetime=50


""""""""""""""""""""""""""""""
" Programing
""""""""""""""""""""""""""""""
" Visual
" From an idea by Michael Naumann
function! VisualSearch(direction) range
  let l:saved_reg = @"
  execute "normal! vgvy"
  let l:pattern = escape(@", '\\/.*$^~[]')
  let l:pattern = substitute(l:pattern, "\n$", "", "")
  if a:direction == 'b'
    execute "normal ?" . l:pattern . "^M"
  else
    execute "normal /" . l:pattern . "^M"
  endif
  let @/ = l:pattern
  let @" = l:saved_reg
endfunction
"Basically you press * or # to search for the current selection !! Really useful
vnoremap <silent> * :call VisualSearch('f')<CR>
vnoremap <silent> # :call VisualSearch('b')<CR>

" Fast grep
nmap <silent> <leader>lv :lv /<c-r>=expand("<cword>")<cr>/ %<cr>:lw<cr>
vmap <silent> <leader>lv :lv /<c-r>=<sid>GetVisualSelection()<cr>/ %<cr>:lw<cr>

" Fast diff
cmap @vd vertical diffsplit 
set diffopt+=vertical

"ctags
"nmap <silent> <leader>tg :!ctags -R --c-kinds=+px --fields=+lS<cr><cr>
"vmap <silent> <leader>tg :!ctags -R --c-kinds=+px --fields=+lS<cr><cr>
nmap <silent> <leader>tg :!ctags -R  --fields=+lS<cr><cr>
vmap <silent> <leader>tg :!ctags -R  --fields=+lS<cr><cr>

"time
nmap <silent> <leader>tm :<ESC>i<C-R>=strftime("%Y-%m-%d")<ESC><ESC>
vmap <silent> <leader>tm :<ESC>i<C-R>=strftime("%Y-%m-%d")<ESC><ESC>

"omni
filetype plugin indent on 
set completeopt=longest,menu

"in file omni
"inoremap <C-p> <C-x><C-n>

"txtbrowser




